﻿-- =============================================
-- Script Template
-- =============================================
USE [DB_Ex]
GO

/****** Object:  StoredProcedure [dbo].[sp_1C_Get_Returns_LastMonth]    Script Date: 12/05/2011 10:39:26 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[sp_1C_Get_Returns_LastMonth]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;


SELECT 
	  RealizaciyaaaTovarovUslug._Number
	, CONVERT(char(10), RealizaciyaaaTovarovUslug._Date_Time, 121) AS Date
	, Skladj._Description AS Sklad
	, Kontragentj._Description AS Kontragent
	, SUM(RealizaciyaaaTovarovUslugTovarj._Fld4689) AS Sum
FROM [DB01].[OU20].[dbo].[_Document186_VT4681] AS RealizaciyaaaTovarovUslugTovarj LEFT OUTER JOIN
		[DB01].[OU20].[dbo].[_Document186] AS RealizaciyaaaTovarovUslug LEFT OUTER JOIN
		[DB01].[OU20].[dbo].[_Reference75] AS Skladj ON RealizaciyaaaTovarovUslug._Fld4667RRef = Skladj._IDRRef LEFT OUTER JOIN
		[DB01].[OU20].[dbo].[_Reference43] AS Kontragentj ON RealizaciyaaaTovarovUslug._Fld4662RRef = Kontragentj._IDRRef ON 
		RealizaciyaaaTovarovUslugTovarj._Document186_IDRRef = RealizaciyaaaTovarovUslug._IDRRef
WHERE (RealizaciyaaaTovarovUslug._Posted = 1) AND (Kontragentj._ParentIDRRef = 0x815e000a5e5c6b8511dc27f35e2208e9)
GROUP BY RealizaciyaaaTovarovUslug._Number, CONVERT(char(10), RealizaciyaaaTovarovUslug._Date_Time, 121), Skladj._Description, Kontragentj._Description
UNION ALL
SELECT 
	  VozvratTovarovPostavchhhiku._Number
	, CONVERT(char(10), VozvratTovarovPostavchhhiku._Date_Time, 121) AS Expr1
	, Skladj._Description
	, Kontragentj._Description AS Expr2
	, VozvratTovarovPostavchhhiku._Fld1986
FROM [DB01].[OU20].[dbo].[_Document105] AS VozvratTovarovPostavchhhiku LEFT OUTER JOIN
		[DB01].[OU20].[dbo].[_Reference75] AS Skladj ON VozvratTovarovPostavchhhiku._Fld1978RRef = Skladj._IDRRef LEFT OUTER JOIN
		[DB01].[OU20].[dbo].[_Reference43] AS Kontragentj ON VozvratTovarovPostavchhhiku._Fld1980RRef = Kontragentj._IDRRef
WHERE (VozvratTovarovPostavchhhiku._Posted = 1) AND (Kontragentj._ParentIDRRef = 0x815e000a5e5c6b8511dc27f35e2208e9)
GROUP BY Skladj._Description, Kontragentj._Description, VozvratTovarovPostavchhhiku._Number, CONVERT(char(10), VozvratTovarovPostavchhhiku._Date_Time, 121), 
		VozvratTovarovPostavchhhiku._Fld1986
ORDER BY Date DESC, Sklad, Kontragent

END

GO


